﻿using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace JianZhangTool.statistics
{
    /// <summary>
    /// 管理上舰信息
    ///     
    ///     程序缓存使用json
    ///     导入导出 使用xlsx
    /// </summary>
    public class RoomGuardInfos
    {
        /// <summary>
        /// 所有信息
        /// </summary>
        private Dictionary<int, GuardInfo> infos = new Dictionary<int, GuardInfo>();
        /// <summary>
        /// 初始房间号
        /// </summary>
        private int origin_roomId;
        /// <summary>
        /// 是否有更改
        /// </summary>
        private bool change = false;
        /// <summary>
        /// 文件名
        /// </summary>
        private string file_name;

        public RoomGuardInfos(int origin_roomId)
        {
            this.origin_roomId = origin_roomId;
            LoadCache();
        }

        /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <returns></returns>
        public List<GuardInfo> GetInfoList()
        {
            List<GuardInfo> ret = new List<GuardInfo>();
            foreach (KeyValuePair<int, GuardInfo> pair in infos)
            {
                GuardInfo guardInfo = pair.Value;
                ret.Add(guardInfo);
            }
            return ret;
        }

        /// <summary>
        /// 根据UID获取舰长信息
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public GuardInfo GetGuardInfoByUID(int uid)
        {
            return infos[uid];
        }

        /// <summary>
        /// 加载缓存
        /// </summary>
        private void LoadCache()
        {
            // 读取信息
            string file_path = Environment.CurrentDirectory + @"\caches\";
            file_name = file_path + origin_roomId + ".json";
            if (!Directory.Exists(file_path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(file_path);
                directoryInfo.Create();
            }

            // 读取Json结构
            JArray json_infos = null;
            if (File.Exists(file_name))
            {
                try
                {
                    string json_str = File.ReadAllText(file_name, Encoding.UTF8);
                    json_infos = JArray.Parse(json_str);
                }
                catch (Exception)
                {
                    // 不做处理
                }
            }
            if (json_infos == null)
            {
                // 没有加载到Json 则赋值空Json结构
                json_infos = JArray.Parse("[]");
            }
            // 转换为信息
            for (int i = 0; i < json_infos.Count; i++)
            {
                JToken jt = json_infos[i];
                GuardInfo guardInfo = GuardInfo.Parse(jt);
                if (guardInfo != null)
                {
                    infos[guardInfo.uid] = guardInfo;
                }
            }
        }

        /// <summary>
        /// 标记数据更改
        /// </summary>
        public void MarkChange()
        {
            lock (save_lock)
            {
                change = true;
            }
        }

        /// <summary>
        /// 存储锁
        /// </summary>
        private readonly object save_lock = new object();

        /// <summary>
        /// 存储
        /// </summary>
        public void Save()
        {
            // 存储上锁 避免协程的多线程问题
            lock (save_lock)
            {
                try
                {
                    if (change)
                    {
                        JArray json_infos = new JArray();
                        foreach (KeyValuePair<int, GuardInfo> pair in infos)
                        {
                            GuardInfo guardInfo = pair.Value;
                            json_infos.Add(guardInfo.ToJson());
                        }
                        StreamWriter sw = new StreamWriter(file_name, false, Encoding.UTF8);
                        if (sw != null)
                        {
                            try
                            {
                                sw.Write(json_infos.ToString());
                                sw.Flush();
                                sw.Close();
                            }
                            finally
                            {
                                sw.Close();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // 不影响锁的释放
                }
            }
        }
    }
}
